//
//  ITNetWorkRequestManager.m
//  GLPFinance
//
//  Created by ITBE on 2016/12/15.
//  Copyright © 2016年 intube. All rights reserved.
//

#import "ITNetWorkRequestManager.h"
#import "ITAppStartManager.h"
#import "ITGeneralManager.h"
@implementation ITNetWorkRequestManager
+ (instancetype)shareManager{
    static ITNetWorkRequestManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (manager == nil) {
            manager = [[self alloc] init];
        }
    });
    return manager;
}

/**
 
 -100    当前版本不支持，请升级后重试。
 200    成功
 401    请登录（未登录）
 402    请登录后体验完整功能（游客登录）
 403    无权限（请求别人的数据或不开放数据）
 404    资源不存在
 406    非法请求（伪造请求或请求不合法）
 410    资源已删除
 412    未进行实名认证（前期绑定手机号）
 422    包含敏感内容（关键字，用户名修改时判断）
 423    资源被锁定
 500    系统异常，请稍后重试！
 503    服务不可用（常用于服务升级中）
 504    您的请求过于频繁，请休息片刻

 */

- (void)analyzedResponse:(ITNetWorkModel *)ret isNotify:(BOOL)isNotify{
    if (ret) {
        id message = ret.message;
        switch (ret.code) {
            case 200:{
                
            }
                break;
            case 401:{//未登录?
                [AppUtils trackMTAEventNo:@"vq_00104"];
                if (isNotify) {
                    [AppUtils showInfo:ret.message];
                }
                //*
                [[ITUserManager shareManager] loginout];
                [[ITUserManager shareManager] activeDevice:nil];//*/
            }
                break;
            case -100:{//当前版本不支持，请升级后重试
                [self alertForceUpdate];
            }
                break;
                
            default:{
                if (isNotify) {
                    if (ret.error) {
                        [AppUtils showInfo:message];
                    }else {
                        [AppUtils showInfo:message];
                    }
                }
            }
                break;
        }
    }
}


- (void)handel:(ITNetWorkModel *)ret callback:(APIRequstCallBack)callback isNotify:(BOOL)isNotify{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self analyzedResponse:ret isNotify:isNotify];
        if (callback) callback(ret);
    });
}


- (NSURLSessionDataTask *)goRequest:(NSString *)uri method:(NSString*)method parameters:(id)parameters callback:(APIRequstCallBack)callback isNotify:(BOOL)isNotify{
    return [[ITNetWorkManager defaultManager] goRequest:uri method:method parameters:parameters callback:^(ITNetWorkModel *ret) {
        [self handel:ret callback:callback isNotify:isNotify];
    }];
}

- (NSURLSessionDataTask *)request:(NSString *)uri method:(NSString *)method parameters:(id)parameters callback:(APIRequstCallBack)callback isNotify:(BOOL)isNotify{
    return [[ITNetWorkManager defaultManager] request:uri method:method parameters:parameters callback:^(ITNetWorkModel *ret) {
        [self handel:ret callback:callback isNotify:isNotify];
    }];
}

- (NSURLSessionDataTask *)get:(NSString *)uri parameters:(id)parameters callback:(APIRequstCallBack)callback isNotify:(BOOL)isNotify{
    return [self goRequest:uri method:@"GET" parameters:parameters callback:callback isNotify:isNotify];
}

- (NSURLSessionDataTask *)post:(NSString *)uri parameters:(id)parameters callback:(APIRequstCallBack)callback isNotify:(BOOL)isNotify{
    return [self goRequest:uri method:@"POST" parameters:parameters callback:callback isNotify:isNotify];
}

- (NSURLSessionDataTask *)put:(NSString *)uri parameters:(id)parameters callback:(APIRequstCallBack)callback isNotify:(BOOL)isNotify{
    return [self goRequest:uri method:@"PUT" parameters:parameters callback:callback isNotify:isNotify];
}

- (NSURLSessionDataTask *)doDelete:(NSString *)uri parameters:(id)parameters callback:(APIRequstCallBack)callback isNotify:(BOOL)isNotify{
    return [self goRequest:uri method:@"DELETE" parameters:parameters callback:callback isNotify:isNotify];
}

- (void)uploadImage:(UIImage *)image uri:(NSString *)uri parameters:(id)parameters callback:(APIRequstCallBack)callback isNotify:(BOOL)isNotify{
    [[ITNetWorkManager defaultManager] uploadImage:image uri:uri parameters:parameters success:^(ITNetWorkModel *ret) {
        [self analyzedResponse:ret isNotify:isNotify];
        dispatch_async(dispatch_get_main_queue(), ^{
            callback(ret);
        });
    } failed:^(ITNetWorkModel *ret) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (isNotify) {
                [self alertWarning];
            }
            ret.errorMsg = [ret.error localizedDescription];
            callback(ret);
        });
    }];
}

- (void)alertWarning{
    if (![AppUtils DICT_WORK_MODE]) {
        return;
    }
    [AppUtils showInfo:[AppUtils titleForKey:@"network is shutdown"]];
}

- (void)alertForceUpdate{
    if (![AppUtils DICT_WORK_MODE]) {
        return;
    }
    if (alertVC == nil) {
        alertVC = [UIAlertController alertControllerWithTitle:[AppUtils titleForKey:@"Notify"] message:[AppUtils titleForKey:@"please update before use"] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:[AppUtils titleForKey:@"comfirm"] style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            self->alertVC = nil;
            NSArray *aa = @[];
            id  a = [aa objectAtIndex:1];
        }];
        [alertVC addAction:cancelAction];
        NSMutableAttributedString *str = [NSMutableAttributedString generateAttriuteStringWithStr:[AppUtils titleForKey:@"please update before use"] WithColor:[UIColor blackColor] WithFont:[UIFont systemFontOfSize:[UIFont systemFontSize]]];
        [alertVC setValue:str forKey:@"attributedMessage"];
        alertVC.modalPresentationStyle = UIModalPresentationFullScreen;
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVC animated:YES completion:^{
            
        }];
    }
}
@end
